package com.addressbook.fw;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;

public abstract class WebDriverHelperBase extends HelperBase {

	protected WebDriver driver;
	

	public WebDriverHelperBase(ApplicationManager manager) {
		super(manager);		
		driver = manager.getDriver();
	}

	/*private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	private boolean isAlertPresent() {
		try {
			driver.switchTo().alert();
			return true;
		} catch (NoAlertPresentException e) {
			return false;
		}
	}*/

	private String closeAlertAndGetItsText() {
		try {
			Alert alert = driver.switchTo().alert();
			String alertText = alert.getText();
			if (manager.acceptNextAlert) {
				alert.accept();
			} else {
				alert.dismiss();
			}
			return alertText;
		} finally {
			manager.acceptNextAlert = true;
		}
	}

	protected void type(String locator, String text) {
		if (text != null) {
			driver.findElement(By.name(locator)).clear();
			driver.findElement(By.name(locator)).sendKeys(text);
		}
	}

	protected void selectByText(String locator, String text) {
		if (text != null) {
			new Select(driver.findElement(By.name(locator)))
					.selectByVisibleText(text);
		}
	}

	protected void click(By by) {
		driver.findElement(by).click();
	}

	protected String getTextByName(String name) {
		return driver.findElement(By.name(name)).getText();
	}
	
	protected String getValueByName(String name) {
		return driver.findElement(By.name(name)).getAttribute("value");
	}
}
